package com.example.hxds.dr.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.example.hxds.common.exception.HxdsException;
import com.example.hxds.common.util.MicroAppUtil;
import com.example.hxds.common.util.PageUtils;
import com.example.hxds.common.util.R;
import com.example.hxds.dr.db.dao.DriverDao;
import com.example.hxds.dr.db.dao.DriverSettingsDao;
import com.example.hxds.dr.db.dao.WalletDao;
import com.example.hxds.dr.db.pojo.DriverSettingsEntity;
import com.example.hxds.dr.db.pojo.WalletEntity;
import com.example.hxds.dr.service.DriverService;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.iai.v20200303.IaiClient;
import com.tencentcloudapi.iai.v20200303.models.CreatePersonRequest;
import com.tencentcloudapi.iai.v20200303.models.CreatePersonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Value;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class DriverServiceImpl implements DriverService {

    @Value("${tencent.cloud.secretId}")
    private String secretId;

    @Value("${tencent.cloud.secretKey}")
    private String secretKey;

    @Value("${tencent.cloud.face.groupName}")
    private String groupName;

    @Value("${tencent.cloud.face.region}")
    private String region;

    @Resource
    private MicroAppUtil microAppUtill;

    @Resource
    private DriverDao driverDao;

    @Resource
    private WalletDao walletDao;

    @Resource
    private DriverSettingsDao driverSettingsDao;

    @Override
    @Transactional
    @LcnTransaction // 分布式事务
    public String registerNewDriver(Map param)
    {
        String code = MapUtil.getStr(param,"code");
        String openId = microAppUtill.getOpenId(code);

        HashMap tempParam = new HashMap<>(){{
            put("openId",openId);
        }};

        if (driverDao.hasDriver(tempParam) != 0)
        {
            throw new HxdsException("该微信无法注册");
        }

        param.put("openId",openId);
        driverDao.registerNewDriver(param); // 插入司机记录
        String driverId = driverDao.searchDriverId(openId);// 查询司机主键值

        // 添加司机设置记录
        DriverSettingsEntity settingsEntity = new DriverSettingsEntity();
        settingsEntity.setDriverId(Long.parseLong(driverId));
        JSONObject json = new JSONObject();
        json.set("orientation","");
        json.set("listenService",true);
        json.set("orderDistance",0);
        json.set("rangeDistance",5);
        json.set("autoAccept",false);
        settingsEntity.setSettings(json.toString());
        driverSettingsDao.insertDriverSettings(settingsEntity);

        // 添加司机钱包记录
        WalletEntity walletEntity = new WalletEntity();
        walletEntity.setDriverId(Long.parseLong(driverId));
        walletEntity.setBalance(new BigDecimal("0"));
        walletEntity.setPassword(null); // 支付密码为空，用户支付时，会提示自动设置
        walletDao.insert(walletEntity);

        return driverId;
    }

    /**
     * 更新司机信息
     * @param param
     * @return
     */
    @Override
    @Transactional
    @LcnTransaction
    public int updateDriverAuth(Map param)
    {
        int rows = driverDao.updateDriverAuth(param);
        return rows;
    }

    /**
     * 创建司机人脸信息
     * @param driverId
     * @param photo
     * @return
     */
    @Override
    public String createDriverFaceModel(long driverId, String photo)
    {
        // 查询司机的姓名和性别
        HashMap map = driverDao.searchDriverNameAndSex(driverId);
        String name = MapUtil.getStr(map, "name");
        String sex = MapUtil.getStr(map, "sex");
        // 调用腾讯云api，实现人员入库
        Credential cred = new Credential(secretId,secretKey);
        IaiClient client = new IaiClient(cred,region);
        try {
            CreatePersonRequest req = new CreatePersonRequest();
            // 设置人员信息
            req.setGroupId(groupName);
            req.setPersonId(Long.toString(driverId));
            long gender = sex.equals("男") ? 1L:2L;
            req.setGender(gender);
            req.setQualityControl(4L);
            req.setUniquePersonControl(4L);
            req.setPersonName(name);
            req.setImage(photo);
            // 执行人员入库
            CreatePersonResponse resp = client.CreatePerson(req);
            if(StrUtil.isNotBlank(resp.getFaceId()))
            {
                int rows = driverDao.updateDriverArchive(driverId);
                if (rows != 1)
                {
                    return  "更新司机归档字段失败！";
                }
            }
        } catch (TencentCloudSDKException e) {
            log.error("创建腾讯云司机端档案失败",e);
            return "创建腾讯云司机端档案失败";
        }

        return "";
    }

    /**
     * 司机登录
     * @param code
     * @return
     */
    @Override
    public HashMap login(String code)
    {
        String openId = microAppUtill.getOpenId(code);
        HashMap result = driverDao.login(openId);
        if (result != null  && result.containsKey("archive"))
        {
            int temp = MapUtil.getInt(result, "archive");
            boolean archive = temp==1?true:false;
            result.replace("archive",archive);
        }
        return result;
    }

    /**
     * 查询司机的基本信息
     * @param driverId
     * @return
     */
    @Override
    public HashMap searchDriverBaseInfo(long driverId)
    {
        HashMap result = driverDao.searchDriverBaseInfo(driverId);
        // 将查询拿到的summary字符串转为json对象
        JSONObject summary = JSONUtil.parseObj(MapUtil.getStr(result, "summary"));
        // 将转换好的对象放回到结果中
        result.replace("summary",summary);
        return result;
    }

    /**
     * 分页查询司机信息
     * @param param
     * @return
     */
    @Override
    public PageUtils searchDriverByPage(Map param)
    {
        long count = driverDao.searchDriverCount(param);
        ArrayList<HashMap> list = new ArrayList<>();
        if (count != 0)
        {
            list = driverDao.searchDriverByPage(param);
        }
        int start = (Integer) param.get("start");
        int length = (Integer) param.get("length");

        PageUtils pageUtils = new PageUtils(list, count, start, length);
        return pageUtils;
    }

    @Override
    public long searchDriverCount(Map param)
    {
        long count = driverDao.searchDriverCount(param);
        return count;
    }


    @Override
    public HashMap searchDriverAuth(long driverId)
    {
        HashMap map = driverDao.searchDriverAuth(driverId);
        return map;
    }
}
